package com.xiaomai.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaomai.eduservice.entity.EduSubject;
import com.xiaomai.eduservice.entity.excel.SubjectData;
import com.xiaomai.eduservice.entity.subject.OneSubject;
import com.xiaomai.eduservice.entity.subject.TwoSubject;
import com.xiaomai.eduservice.listenter.SubjectExcelListenter;
import com.xiaomai.eduservice.mapper.EduSubjectMapper;
import com.xiaomai.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2021-08-28
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    //保持从Excel获取的数据到数据库
    @Override
    public void saveSubject(MultipartFile file,EduSubjectService subjectService) {

        try {
            InputStream in = file.getInputStream();
            EasyExcel.read(in, SubjectData.class,new SubjectExcelListenter(subjectService)).sheet().doRead();
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    //获得所有的一级二级课程
    @Override
    public List<OneSubject> getOneTwoSubject() {
        //查询所有的一级
        QueryWrapper<EduSubject>  wrapperOne = new QueryWrapper<>();
        wrapperOne.eq("parent_id","0");
        List<EduSubject> oneSubjectList = baseMapper.selectList(wrapperOne);//查到后封装到oneSubjectList集合里面


        //查询所有的二级
        QueryWrapper<EduSubject>  wrapperTwo = new QueryWrapper<>();
        wrapperTwo.ne("parent_id","0");
        List<EduSubject> twoSubjectList = baseMapper.selectList(wrapperTwo);

        //创建出一个最终集合遍历一级，然后在一级中遍历二级
        List<OneSubject> finalSubjectList = new ArrayList<>();

        for (EduSubject eduSubject : oneSubjectList) {
            OneSubject oneSubject = new OneSubject();
            //将从数据库获取到的一级放进OneSubject对象里面
            BeanUtils.copyProperties(eduSubject,oneSubject);
            //将oneSubject放进最终集合里面
            finalSubjectList.add(oneSubject);
            //创建一个集合放一级里面的多个二级
            List<TwoSubject> twofinalSubjectsList = new ArrayList<>();

            for (EduSubject tSubject : twoSubjectList) {
                if(tSubject.getParentId().equals(oneSubject.getId())){
                    //将每个符合条件的二级放进集合里面
                        TwoSubject twoSubject = new TwoSubject();
                        BeanUtils.copyProperties(tSubject,twoSubject);
                    twofinalSubjectsList.add(twoSubject);
                }
            }
            //最后将封装二级的集合放到每个一级对象里面
           oneSubject.setChildren(twofinalSubjectsList);
        }
        return finalSubjectList;
    }
}
